<template>
  <div class="app-container">
    <!-- <el-row :gutter="20"> -->

      <!--用户数据-->
      <!-- <el-col :span="20" :xs="24"> -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="用户账号" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户账号"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
<!--          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
            >导出</el-button>
          </el-col>-->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>


        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="客户ID" align="center" key="userId" prop="userId"  />
          <el-table-column label="用户账号" align="center" key="userName" prop="userName"   />
          <el-table-column label="用户别名" align="center" key="nickName" prop="nickName"></el-table-column>
          <el-table-column label="所在城市" align="center" key="city" prop="city"  >
            <template slot-scope="scope">
              <span> {{ scope.row.province}}</span>
              <span> {{ scope.row.city}}</span>
              <span> {{ scope.row.area}}</span>
            </template>

          </el-table-column>
          <el-table-column label="注册时间" align="center" prop="createTime" >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

    <!-- 客户绑定的设备列表 -->
    <el-dialog title="绑定设备列表" :visible.sync="dialogTableVisible">
      <el-table :data="equList">
        <el-table-column property="snCode" label="设备SN码" width="150"></el-table-column>
        <el-table-column property="equipmentName" label="设备名称" width="200"></el-table-column>
        <el-table-column property="equipmentModel" label="设备型号" width="150"></el-table-column>
        <el-table-column property="createTime" label="绑定时间" width="150"></el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="160"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope" v-if="scope.row.userId !== 1">
            <el-button
              size="mini"
              type="danger"
              plain
              icon="el-icon-delete"
              @click="handleOpen(scope.row)"
            >解绑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-drawer
      title="档案管理"
      :visible.sync="drawTable"
      direction="rtl"
      size="60%">
      <el-table v-loading="loading" :data="dossierList" >
        <el-table-column label="客户ID" align="center" key="id" prop="id"  />
        <el-table-column label="档案名称" align="center" key="surname" prop="surname"   />
        <el-table-column label="性别" align="center" key="sex" prop="sex">
          <template slot-scope="scope">
            <span style="color: #00afff;" v-if="scope.row.sex==1">男</span>
            <span style="color: #00afff;" v-if="scope.row.sex==2">女</span>
          </template>
        </el-table-column>
        <el-table-column label="出生日期" align="center" key="birthday" prop="birthday"></el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="修改时间" align="center" prop="createTime" >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="200"
          class-name="small-padding fixed-width"
        >

          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                       >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteDossier(scope.row)"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-order"
              @click="findTemRecord(scope.row)"
            >测温记录</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="dtotal>0"
        :total="dtotal"
        :page.sync="dqueryParams.pageNum"
        :limit.sync="dqueryParams.pageSize"
        @pagination="getClientList"
      />
    </el-drawer>
    <!-- 添加或修改档案管理的对话框 -->
    <el-dialog :title="title" :visible.sync="dossierOpen" v-if="dossierOpen"  width="500px" append-to-body>
      <el-form ref="dossierForm" :model="dossierForm" :rules="rules" label-width="80px">
        <el-form-item label="档案名称" prop="surname">
          <el-input v-model="dossierForm.surname" placeholder="请输入档案名称" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-select
            v-model="dossierForm.sex"
            placeholder="用户状态"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in sexs"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker clearable v-model="dossierForm.birthday" type="date" value-format="yyyy-MM-dd" placeholder="请选择生日">
          </el-date-picker>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelDossier">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="cewenTitle" :visible.sync="cewenOpen" v-if="cewenOpen"  width="900px" append-to-body>
      <el-table v-loading="loading" :data="cewenList" >

        <el-table-column label="日期" align="center" prop="createTime" >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}')}}</span>
          </template>
        </el-table-column>
        <el-table-column label="最高温度" align="center" prop="temperature" ></el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="260"
          class-name="small-padding fixed-width"
        >

          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="findEvents(scope.row)">事件记录</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="remindRecord(scope.row)"
            >提醒记录</el-button>
<!--            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-order"
              @click="temLine(scope.row)"
            >温度曲线</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="cwtotal>0"
        :total="cwtotal"
        :page.sync="cewParams.pageNum"
        :limit.sync="cewParams.pageSize"
        @pagination="getClientList"
      />
    </el-dialog>
    <el-dialog :title="eventTitle" :visible.sync="eventOpen" v-if="eventOpen"  width="50vw" append-to-body>

      <el-table v-loading="loading" :data="eventList" >

        <el-table-column label="日期事件" align="center" prop="createTime" >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.recordTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" prop="thingType" >
          <template slot-scope="scope">
            <span v-if="scope.row.thingType==1">服用退烧药</span>
            <span v-if="scope.row.thingType==2">物理降温</span>
            <span v-if="scope.row.thingType==3">发烧</span>
            <span v-if="scope.row.thingType==4">低温</span>
            <span v-if="scope.row.thingType==5">其他</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="des"></el-table-column>
      </el-table>
      <pagination
        v-show="evtotal>0"
        :total="evtotal"
        :page.sync="evqueryParams.pageNum"
        :limit.sync="evqueryParams.pageSize"
      />
    </el-dialog>
    <!--提醒记录-->
    <el-dialog :title="remindTitle" :visible.sync="remindOpen" v-if="remindOpen"  width="50vw" append-to-body>

      <el-table v-loading="loading" :data="remindList" >

        <el-table-column label="时间" align="center" prop="createTime" >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" prop="type" >
          <template slot-scope="scope">
            <span v-if="scope.row.type==1">高温提醒</span>
            <span v-if="scope.row.type==2">低温提醒</span>
          </template>
        </el-table-column>
        <el-table-column label="温度" align="center" prop="temperature"></el-table-column>
      </el-table>
      <pagination
        v-show="remindtotal>0"
        :total="remindtotal"
        :page.sync="remindtotalParams.pageNum"
        :limit.sync="remindtotalParams.pageSize"
      />
    </el-dialog>
    <!--提醒记录-->
    <el-dialog  :title="lineTitle" :visible.sync="lineOpen" v-if="lineOpen"  width="40vw" append-to-body>
      <div id="lineWen" style="width: 700px;height: 400px;"></div>
    </el-dialog>
  </div>
</template>

<script>
import { clientlistUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus,getEquList,JieBang,lookRecord } from "@/api/system/user";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listDossier,getDossier,addDossier,updateDossier,delDossier,getHighList,selectEvents,selectReminds} from "@/api/kenuo/dossier";
export default {
  name: "docUser",
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  components: { Treeselect },
  data() {
    return {
      lineOpen:false,
      lineTitle:'',
      myChart1:null,
      remindtotal:0,
      remindList:[],
      remindOpen:false,
      remindTitle:"",
      cewParams:{
        pageNum: 1,
        pageSize: 10
      },
      remindtotalParams:{
        pageNum: 1,
        pageSize: 10
      },
      cwtotal:0,
      evqueryParams:{
        pageNum: 1,
        pageSize: 10
      },
      evtotal:0,
      eventList:[],
      eventOpen: false,
      eventTitle: "",
      cewenList: [],
      cewenOpen: false,
      cewenTitle:"",
      dname:"",
      sexs:[
        {
          label:'男',
          value:1
        },
        {
          label:'女',
          value:2
        }
      ],
      dossierOpen:false,
      dossierForm:{},
      dtotal:0,
      dossierList:[],
      drawTable:false,
      dialogTableVisible: false,
      equList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
        userType: "02",
        nickName: null
      },
      // 查询参数
      dqueryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
        sysFlag: 2,
        userType: "02",
        nickName: null
      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      option:{
        title: {
          text: ''
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {},
        toolbox: {
          show: false,
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            dataView: { readOnly: false },
            magicType: { type: ['line', 'bar'] },
            restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} °C'
          }
        },
        series: [
          {
            name: 'Highest',
            type: 'line',
            data: [10, 11, 13, 11, 12, 12, 9],
            markPoint: {
              data: [
                { type: 'max', name: 'Max' },
                { type: 'min', name: 'Min' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            }
          },
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
  },
  methods: {
    //温度曲线
    temLine(row){
        this.lineTitle = '温度曲线';
        this.lineOpen = true;
        selectReminds({
          userName:this.dname,
          remarkThree:row.dossierId,
          createTime:row.createTime
        }).then((response) => {
          this.remindList = response.rows;
          this.remindtotal = response.total;
        });
        this.$nextTick(function(){
        //获取元素
        let chartDom = window.document.getElementById("lineWen");
        this.myChart1 = this.$echarts.init(chartDom);
        this.myChart1.setOption(this.option);
      });
    },
    remindRecord(row){
      this.remindTitle = '提醒记录';
      this.remindOpen = true;
      selectReminds({
        userName:this.dname,
        remarkThree:row.dossierId,
        createTime:row.createTime
      }).then((response) => {
        this.remindList = response.rows;
        this.remindtotal = response.total;
      });
    },
    //查询事件记录
    findEvents(row){
      this.eventTitle = '事件记录';
      this.eventOpen = true;
      selectEvents({
        userName:this.dname,
        remarkTwo:row.dossierId,
        recordTime:row.createTime
      }).then((response) => {
        this.eventList = response.rows;
        this.evtotal = response.total;
      });
    },
    //打开测温记录弹窗
    findTemRecord(row){
        this.cewenTitle = "测温记录";
        this.cewenOpen = true;
        //查询测温记录
      this.cewenRecord(row.id);
    },
    //查询测温记录
    cewenRecord(dosId){
      getHighList({
        "dossierId":dosId
      }).then((response) => {
        this.cewenList = response.rows;
        this.cwtotal = response.total;
      });
    },
    cancelDossier(){
      this.dossierOpen = false;
      this.resetDossier();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["dossierForm"].validate((valid) => {
        if (valid) {
          if (this.dossierForm.id != null) {
            updateDossier(this.dossierForm).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.dossierOpen = false;
              this.getClientList();
            });
          }
        }
      });
    },
    handleDeleteDossier(row) {
      const Ids = row.id || this.ids;
      this.$modal.confirm('确认删除吗？').then(function() {
        return delDossier(Ids);
      }).then(() => {
        this.getClientList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetDossier();
      const id = row.id || this.ids
      getDossier(id).then(response => {
        this.dossierForm = response.data;
        this.dossierOpen = true;
        this.title = "修改档案管理";
        this.getClientList();
      });
    },
    getClientList(){
      this.dossierList =[];
      listDossier({
        remarkOne:this.dname
      }).then(response => {
        this.dossierList = response.rows;
        this.dtotal = response.total;
      })
    },
    resetDossier(){
      this.dossierForm = {
        id: null,
        surname: null,
        sex: null,
        createTime: null,
        updateTime: null,
        birthday:null
      };
      this.resetForm("dossierForm");
    },
    //菜单路由跳转
    roterTo(userName){
      this.drawTable = true;
      this.dname = userName;
      listDossier({
        remarkOne:userName
      }).then(response => {
        this.dossierList = response.rows;
        this.dtotal = response.total;
      })
/*      this.$router.push({
        name: "dossier",
        query: {
          userName: userName
        }
      });*/
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      clientlistUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function() {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
